package util;

import config.ApplicationConfig;
import net.sf.json.JSONObject;

import java.io.*;
import java.util.Iterator;
import java.util.LinkedHashMap;

/**
 * UserRank: tum0r
 * Package Name: util
 * Time: 2019-01-24 Thursday 15:08:15
 */
public class ReadConfig {
    public LinkedHashMap<String, String> readConfig(String fileName) {
        synchronized (this) {
            try {
                LinkedHashMap<String, String> result = new LinkedHashMap<String, String>();
                File configFile = new File(ApplicationConfig.getPath() + ".." + File.separator + ".." + File.separator + "config" + File.separator + fileName);
                FileInputStream fileInputStream = new FileInputStream(configFile);
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String line;
                StringBuilder stringBuffer = new StringBuilder();
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }
                bufferedReader.close();
                inputStreamReader.close();
                fileInputStream.close();
                JSONObject json = JSONObject.fromObject(stringBuffer.toString());
                Iterator keys = json.keys();
                while (keys.hasNext()) {
                    String key = keys.next().toString();
                    result.put(key, json.getString(key));
                }
                return result;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}
